﻿#include "ConfigMgr.h"
#include "AsioIOServicePool.h"
#include "CServer.h"
#include <iostream>
#include "RedisMgr.h"
#include "ChatServiceImpl.h"
int main()
{
    auto& CfgMgr = ConfigMgr::Inst();
    std::string RPCserver_address = CfgMgr["SelfServer"]["Host"] + ":" + CfgMgr["SelfServer"]["RPCPort"];
    std::string server_address = CfgMgr["SelfServer"]["Host"] + ":" + CfgMgr["SelfServer"]["Port"];
    std::string server_name = CfgMgr["SelfServer"]["Name"];
    auto port_str = CfgMgr["SelfServer"]["Port"];
    try {
        auto pool = AsioIOServicePool::GetInstance();
        boost::asio::io_context  io_context;
        boost::asio::signal_set signals(io_context, SIGINT, SIGTERM);
        RedisMgr::GetInstance()->HSet(LOGIN_COUNT, server_name, "0");
        //启动grpc服务
        ChatServiceImpl service;
        grpc::ServerBuilder builder;                                               //grpc::InsecureServerCredentials():
        builder.AddListeningPort(RPCserver_address, grpc::InsecureServerCredentials());  //客户端和服务器之间的数据传输不经过加密
        builder.RegisterService(&service);
        // 构建并启动gRPC服务器
        std::unique_ptr<grpc::Server> server(builder.BuildAndStart());
        std::cout << "RPC Server listening on " << RPCserver_address << std::endl;
        std::thread grpc_server_thread([&server]() {
            server->Wait();
            });


        signals.async_wait([&io_context, pool,&server](auto, auto) {
            io_context.stop();
            pool->stop();
            server->Shutdown();
            });
        CServer s(io_context, atoi(port_str.c_str()));
        io_context.run();

        RedisMgr::GetInstance()->HDel(LOGIN_COUNT, server_name);
        RedisMgr::GetInstance()->Close();
        grpc_server_thread.join();

    }
    catch (std::exception& e) {
        std::cerr << "exception is" << e.what() << std::endl;
        RedisMgr::GetInstance()->HDel(LOGIN_COUNT, server_name);
        RedisMgr::GetInstance()->Close();
    }
}

